﻿using LogionDemo.Common.Helper;
using LogionDemo.Common.Helper.Enums;
using LogionDemo.Common.UserEventArgs;
using LogionDemo.Controls.Base;
using LogionDemo.Extensions;
using LogionDemo.Models;
using Masuit.Tools.Strings;

namespace LogionDemo
{
	public partial class LoginForm : LoginBaseForm
	{
		private string _captcha = string.Empty;
		private RegisterInfoContext _registerInfoContext = new();
		private UserToken? _userToken;

		public LoginForm()
		{
			InitializeComponent();
			Subscribe(new LoginStatusObserver());
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.Cancel;
		}

		private void btnLogin_Click(object sender, EventArgs e)
		{
			var result = LoginHelper.LoginUser(
				_registerInfoContext,
				txtUser.Text,
				txtPassword.Text,
				userToken =>
				{
					_userToken = userToken;
					CacheHelper.Add(userToken, new() { SlidingExpiration = TimeSpan.FromSeconds(5) });
				},
				(n, p) => _captcha == txtCaptcha.Text
			);
			string message = result switch
			{
				LoginResult.Success => $"登录成功。欢迎你{txtUser.Text}。",
				LoginResult.UserNameEmpty => "用户名不可为空，请重新输入。",
				LoginResult.PasswordEmpty => "密码不可为空，请重新输入。",
				LoginResult.UserNotFound => "用户名不存在，请检查输入或注册新账户。",
				LoginResult.InvalidPassword => "密码错误，请重新输入。",
				LoginResult.AdditionalValidationFailed => "验证码错误，请输入正确的验证码！",
				_ => "未知错误，请联系支持。" // 默认情况
			};

			if (result is LoginResult.Success)
			{
				Publish(new LoginStatusChangedEventArgs(true, _userToken!));
				MessageBox.Show(message, "登录信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
				_registerInfoContext.SetLoginSavePasswordConfig(txtUser.Text, txtPassword.Text, cbRemeber.Checked);
				DialogResult = DialogResult.OK;
			}
			else
			{
				MessageBox.Show(message, "登录信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
				RefreshCaptcha();
			}
		}

		private void btnRegister_Click(object sender, EventArgs e)
		{
			var result = LoginHelper.RegisterUser(_registerInfoContext, txtUser.Text, txtPassword.Text, (n, p) => _captcha == txtCaptcha.Text);
			string message = result switch
			{
				RegisterResult.Success => $"注册成功,{txtUser.Text}。",
				RegisterResult.UserNameEmpty => "用户名不可为空，请重新输入。",
				RegisterResult.PasswordEmpty => "密码不可为空，请重新输入。",
				RegisterResult.InvalidUserName => "用户名已存在，请重新输入。",
				RegisterResult.AdditionalValidationFailed => "验证码错误，请输入正确的验证码！",
				_ => "未知错误，请联系支持。" // 默认情况
			};
			if (result is RegisterResult.Success)
			{
				MessageBox.Show(message, "登录信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
				RefreshCaptcha();
			}
			else
			{
				MessageBox.Show(message, "登录信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
				RefreshCaptcha();
			}
		}

		private void cbCheckPassword_CheckedChanged(object sender, EventArgs e)
		{
			var cb = sender as CheckBox;

			if (cb!.Checked)
			{
				txtPassword.PasswordChar = '\0';
			}
			else
			{
				txtPassword.PasswordChar = '*';
			}
		}

		private void Login_Load(object sender, EventArgs e)
		{
			RefreshCaptcha();
			var config = _registerInfoContext.GetLoginSavePasswordConfig();
			cbRemeber.Checked = config.IsRemember;
			txtPassword.Text = config.Password;
			txtUser.Text = config.User;
		}

		#region private methods

		private void picRefresh_Click(object sender, EventArgs e)
		{
			RefreshCaptcha();
		}

		private void RefreshCaptcha()
		{
			_captcha = ValidateCode.CreateValidateCode(4);
			picCaptcha.Image = Image.FromStream(_captcha.CreateValidateGraphic(35).ToStream());
			//txtCaptcha.Text = string.Empty；
			//自动输入验证码了，否则太麻烦。
			txtCaptcha.Text = _captcha;
		}

		#endregion private methods
	}
}